from flask import Blueprint, render_template, request
from applications.common.utils.rights import authorize
from applications.common.utils.http import table_api, success_api, fail_api
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models.bigScreenData import AgriculturalYield

bp = Blueprint('agricultural', __name__, url_prefix='/agricultural')


@bp.get('/')
@authorize("agricultural:main")
def main():
    return render_template('dataManagement/agricultural/main.html')


# // 编辑页面路由
@bp.get('/edit/<int:id>')
@authorize("agricultural:edit")
def edit(id):
    area = AgriculturalYield.query.get_or_404(id)
    return render_template('dataManagement/agricultural/edit.html', area=area)


@bp.get('/data')
@authorize("agricultural:main")
def data():
    province_name = request.args.get('province_name', type=str)
    year = request.args.get('year', type=str)
    indicator = request.args.get('indicator', type=str)

    filters = []
    if province_name:
        filters.append(AgriculturalYield.province_name.contains(province_name))
    if year:
        filters.append(AgriculturalYield.year == year)
    if indicator:
        filters.append(AgriculturalYield.indicator.contains(indicator))

    query = AgriculturalYield.query.filter(*filters).layui_paginate()

    return table_api(
        data=[{
            'id': item.id,
            'province_code': item.province_code,
            'province_name': item.province_name,
            'year': item.year,
            'indicator': item.indicator,
            'value': item.value,
            'update_time': item.update_time.strftime('%Y-%m-%d %H:%M:%S')
        } for item in query.items],
        count=query.total
    )


# 新增路由：显示新增页面
@bp.get('/add')
@authorize("agricultural:add")
def add():
    return render_template('dataManagement/agricultural/add.html')


# 修改后的保存逻辑（替换原save方法）
@bp.post('/save')
@authorize("agricultural:add")
def save():
    req_json = request.get_json(force=True)

    province_code = str_escape(req_json.get('province_code'))
    province_name = str_escape(req_json.get('province_name'))
    # 添加类型转换和验证
    try:
        year = int(str_escape(req_json.get('year')))
    except ValueError:
        return fail_api(msg="年份必须是整数")
    indicator = str_escape(req_json.get('indicator'))
    try:
        value = int(str_escape(req_json.get('value')))  # 假设受灾面积需要整数类型
    except ValueError:
        return fail_api(msg="受灾面积必须是整数")

    if not all([province_code, province_name, year, indicator, value]):
        return fail_api(msg="所有字段都不能为空")

    # 检查重复数据
    if AgriculturalYield.query.filter_by(
            province_code=province_code,
            year=year,
            indicator=indicator
    ).first():
        return fail_api(msg="该省份/年份/指标组合已存在")

    new_area = AgriculturalYield(
        province_code=province_code,
        province_name=province_name,
        year=year,
        indicator=indicator,
        value=value
    )

    try:
        db.session.add(new_area)
        db.session.commit()
        return success_api(msg="新增成功")
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=f"保存失败: {str(e)}")


@bp.put('/update')
@authorize("agricultural:edit")
def update():
    req_json = request.get_json(force=True)
    id=str_escape(req_json.get('id'))
    province_code = str_escape(req_json.get('province_code'))
    province_name = str_escape(req_json.get('province_name'))
    # 添加类型转换和验证
    try:
        year = int(str_escape(req_json.get('year')))
    except ValueError:
        return fail_api(msg="年份必须是整数")
    indicator = str_escape(req_json.get('indicator'))
    try:
        value = int(str_escape(req_json.get('value')))  # 假设受灾面积需要整数类型
    except ValueError:
        return fail_api(msg="受灾面积必须是整数")

    if not all([province_code, province_name, year, indicator, value]):
        return fail_api(msg="所有字段都不能为空")

    AgriculturalYield.query.filter_by(id=id).update(dict(
        province_code=province_code,
        province_name=province_name,
        year=year,
        indicator=indicator,
        value=value
    ))

    try:
        db.session.commit()
        return success_api(msg="更新成功")
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=f"更新失败: {str(e)}")


@bp.delete('/delete/<int:id>')
@authorize("agricultural:remove")
def delete(id):
    area = AgriculturalYield.query.get(id)
    if not area:
        return fail_api(msg="数据不存在")
    try:
        db.session.delete(area)
        db.session.commit()
        return success_api(msg="删除成功")
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=f"删除失败: {str(e)}")


@bp.get('/indicators')
@authorize("agricultural:main")
def get_indicators():
    # 从数据库中获取所有不重复的指标
    indicators = db.session.query(AgriculturalYield.indicator.distinct()).all()
    # 将结果转换为一维列表
    indicator_list = [indicator[0] for indicator in indicators]
    return table_api(msg="获取成功", data=indicator_list)
